<?php

namespace App\Http\Controllers\Api;

use App\Http\Logic\CategoryLogic;
use App\Http\Requests\Api\CategoryRequest;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    public function index(Request $request)
    {
        $request = $this->handleRequestPage($request->all(), $this->pageSize);
        $result = CategoryLogic::logic()->index($request);
        return $this->success('成功', $result);
    }

    public function store(CategoryRequest $categoryRequest)
    {
        $request = $categoryRequest->only(['category_name']);

        $result = CategoryLogic::logic()->store($request);
        return $this->success('添加成功', $result);
    }

    public function update($id, Request $request)
    {
        $request = $request->only(['category_name']);

        // 规则类 注意不要直接注入到方法中,否则默认会先验证rules
        $categoryRequest = new CategoryRequest();
        $this->validatesRequests($request, $categoryRequest->updateRules(), $categoryRequest->updateMessages());

        CategoryLogic::logic()->update($id, $request);
        return $this->success('修改成功');
    }

    /**
     * 修改排序
     * @param $id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sort($id, Request $request)
    {
        $request = $request->only(['target_sort']);

        // 规则类
        $categoryRequest = new CategoryRequest();
        $this->validatesRequests($request, $categoryRequest->sortRules(), $categoryRequest->sortMessages());

        $result = CategoryLogic::logic()->sort($id, $request);
        return $result ? $this->success('修改成功') : $this->error();
    }
}
